//
//  AddDiaryContentViewController.swift
//  MoodDiary
//
//  Created by ext.tanjian3 on 2022/1/18.
//

import UIKit
import CoreMedia
import ReactiveCocoa
import SVProgressHUD
import AVFoundation


@objc enum AddDiaryContentVCType:Int {
    case typeNew  = 0      //新建
    case typeEdit = 1     //编辑
    case typeDetail = 2   //详情展示
}

@objc protocol AddDiaryContentViewControllerDelegate: AnyObject {
    
    @objc optional func attriButeEditing(attriStr:NSAttributedString?)
    @objc optional func attributeEditDone(dict:NSDictionary?,attriStr:NSAttributedString?)
    @objc optional func diaryDelete(index:Int,timeStamp:String)
   
}


class AddDiaryContentViewController: UIViewController{

    @objc var pageType: AddDiaryContentVCType = .typeNew
    
    var diaryModel: DiaryModel?

    @objc var diaryDict: [String: Any]?
    
    var isBadXinqing: Bool = false
    
    var tempAttrStr:NSAttributedString?
    
    var reasonArray:[[String:Any]] = AppConstant.activeDatasArr
    
    let imgPickerVC:UIImagePickerController = UIImagePickerController()
    
    var alert:CustomDialogueController?
    
    var saveAlert:CustomDialogueController?
    
    var photoStyleChooseView = PhotoStyleChooseView()
    
    @objc weak var delegate: AddDiaryContentViewControllerDelegate?
    
    @objc var editIndex:Int = -1 // 编辑的那一条数据，为DiaryForDayController使用
    
    var tempAttr:NSAttributedString?
    
    @IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var weatherImgView: UIImageView!
    @IBOutlet weak var weatherNameLabel: UILabel!
    @IBOutlet weak var weatherSepLine: UIView!
    @IBOutlet weak var activesCollectionView: UICollectionView!
    @IBOutlet weak var moodImgView: UIImageView!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var bgTextView: UITextView!
    @IBOutlet weak var contentTextView: UITextView!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var imgCountLabel: UILabel!
    @IBOutlet weak var bottomSpLine: UIView!
    @IBOutlet weak var timeBtn: UIButton!
    @IBOutlet weak var alagnBtn: UIButton!
    
    @IBOutlet weak var textviewBottomConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if diaryModel == nil{
            
            diaryModel = DiaryModel.init()
            diaryModel?.timeStampStr = diaryDict?["timeStampStr"] as? String
            diaryModel?.moodStr = diaryDict?["moodStr"] as? String
            diaryModel?.weatherStr = diaryDict?["weatherStr"] as? String
            diaryModel?.reasonArray = diaryDict?["reasonArray"] as? Array
            diaryModel?.reasonDetailStr = diaryDict?["reasonDetailStr"] as? String
            diaryModel?.createTimeStampStr = diaryDict?["createTimeStampStr"] as? String
            
        }else if diaryModel != nil{
        
            diaryDict?["timeStampStr"] = diaryModel?.timeStampStr
            diaryDict?["moodStr"] = diaryModel?.moodStr
            diaryDict?["weatherStr"] = diaryModel?.weatherStr
            diaryDict?["reasonArray"] =  diaryModel?.reasonArray
            diaryDict?["reasonDetailStr"] = diaryModel?.reasonDetailStr
            diaryDict?["createTimeStampStr"] = diaryModel?.createTimeStampStr
            
        }
        
        let placeHolderLabel:UILabel = UILabel.init()
        placeHolderLabel.text = "有更多想告诉我的吗？"
        placeHolderLabel.numberOfLines = 0
        placeHolderLabel.textColor = UIColor.hexColor(hex: "#939393")
        placeHolderLabel.font = UIFont.systemFont(ofSize: 14)
        contentTextView.addSubview(placeHolderLabel)
        contentTextView.setValue(placeHolderLabel, forKey: "_placeholderLabel")
        
        
        self.configUI()
        
        self.configKeybordAction()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        activesCollectionView.flashScrollIndicators()
        
    }

    
    func configUI() {
        
        self.configBaseUI()
        
        weatherImgView.image = UIImage.init(named: diaryModel?.weatherStr ?? "晴天")
        weatherNameLabel.text = diaryModel?.weatherStr ?? "晴天"
        
        self.configmoodUI()
        
        self.configActivesUI()

        self.timeLabel.text = NSString.getHourAndMinute(NSString.currentTimeStamp())
        if pageType != .typeNew{
            self.timeLabel.text = NSString.getHourAndMinute(diaryModel?.createTimeStampStr ?? NSString.currentTimeStamp())
        }
        
        self.configTextViewUI()

        self.configBottomUI()
    }
    
    func configBaseUI() {
        
        if let timeStampStr: String = diaryModel?.timeStampStr{
            let navTitle = NSString.convertTimeStamp(toMH: timeStampStr)
            navigationItem.title = navTitle
        }
        
        
        bgTextView.backgroundColor = UIColor.hexColor(hex: "#FAFAFA")
        bgTextView.layer.borderColor = UIColor.hexColor(hex: "#E8E8E8 ").cgColor
        bgTextView.layer.borderWidth = 1
        contentTextView.backgroundColor = UIColor.hexColor(hex: "#FAFAFA")
        contentTextView.delegate = self
        weatherNameLabel.textColor = UIColor.hexColor(hex: "#939393")
        timeLabel.textColor = UIColor.hexColor(hex: "#939393")
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        activesCollectionView.collectionViewLayout = flowLayout
        
        
        if pageType == .typeDetail{
            navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "store_nav_else")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(saveAction))
        }else{
            navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "编辑确认")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(saveAction))
        }
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "返回"), style: .plain, target: self, action: #selector(closeAction))
    }
    
    func configBottomUI() {
        
        if pageType == .typeDetail{
            
            bottomView.isHidden = true
        }
    }
    
    
    func configActivesUI() {
        
        self.configActiveImagesNames()
        
        if (diaryModel?.reasonArray?.count == 0){
            weatherSepLine.isHidden = true
        }
        
        activesCollectionView.delegate = self
        activesCollectionView.dataSource = self
        
        activesCollectionView.register(UINib(nibName: "ActiveCollectionCellForDiaryContentEditPage", bundle: .main), forCellWithReuseIdentifier: "ActiveCollectionCellForDiaryContentEditPage")
        
        activesCollectionView.reloadData()
    }
    
    func configmoodUI() {
        
        if var imgArray = UserDefaults.standard.array(forKey: KUSERFeelingImagesArrName ) as? [[String:Any]] {
            
            if let imgDeletedArray = UserDefaults.standard.array(forKey: KUSERFeelingDeletedImagesArrName) as? [[String:Any]] {
                
                imgArray.append(contentsOf: imgDeletedArray)
            }
            
            for cacheDict in imgArray {
                if diaryModel?.moodStr == cacheDict["text"] as? String {
                    moodImgView.image = UIImage.init(named: cacheDict["imgName"] as! String)
                    break;
                }
            }
        }
        
    }
    
    func configTextViewUI() {
        
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 8
        let dic:Dictionary = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.paragraphStyle:paragraphStyle]
        contentTextView.typingAttributes = dic
        
        if pageType != .typeNew{
            
            let reasonDetailStr = diaryModel?.reasonDetailStr
            if reasonDetailStr?.contains("isAttributedString") == true  {
                
                let fileManager = FileManager.default
                let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String

                let folderPath = docPath + "/" + (diaryModel?.timeStampStr ?? "") + ".txt"
                
                if let data:Data = fileManager.contents(atPath: folderPath){
                    
                    var attr:NSAttributedString = NSAttributedString.init()
                    
                    if let attriTemp:NSAttributedString = (NSKeyedUnarchiver.unarchiveObject(with: data) as? NSAttributedString){
                        
                        attr = attriTemp
                    }
                    
                    if tempAttrStr != nil{
                        attr = tempAttrStr!
                    }
                    let mutableAttr = NSMutableAttributedString.init(attributedString: attr)
                
                    attr.enumerateAttributes(in: NSMakeRange(0, attr.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, range, stop) in
                        
                        if let textAtt:NSTextAttachment = object[NSAttributedString.Key(rawValue: "NSAttachment")] as? NSTextAttachment {
                            
                            let tempImage:UIImage = textAtt.image!;
                            
                            let scale = tempImage.size.width / tempImage.size.height;
                            var height = 80.0;
                            var width = scale * height;
                            if (scale > 1){
                                width = 80;
                                height = width/scale;
                            }
                            
                            textAtt.bounds = CGRect(x: 0, y: 0, width: width, height: height)
                            mutableAttr.replaceCharacters(in: range, with: NSAttributedString.init(attachment: textAtt))
                        }
                    }
                    
//                    mutableAttr.setAttributes([NSAttributedString.Key.baselineOffset:10], range: NSMakeRange(0, mutableAttr.string.count))
                    let paragraphStyle = NSMutableParagraphStyle.init()
                    paragraphStyle.lineSpacing = 8
                    let dic:Dictionary = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.paragraphStyle:paragraphStyle]
                    mutableAttr.addAttributes(dic, range: NSMakeRange(0, mutableAttr.string.count))
                    
                    contentTextView.attributedText = mutableAttr.copy() as? NSAttributedString
                    
                    if reasonDetailStr?.hasPrefix("1") == true {
                        contentTextView.textAlignment = .center
                        alagnBtn.setImage(UIImage.init(named: "字体对齐图标"), for: .normal)
                    }else if reasonDetailStr?.hasPrefix("2") == true {
                        contentTextView.textAlignment = .right;
                        alagnBtn.setImage(UIImage.init(named: "字体对齐图标右"), for: .normal)
                    }else{
                        contentTextView.textAlignment = .left;
                        alagnBtn.setImage(UIImage.init(named: "字体对齐图标左"), for: .normal)
                    }
                    
                }
            }else{
                
                contentTextView.attributedText = NSAttributedString.init(string: reasonDetailStr ?? "")
            }
            
            self.configImgCount(isPickImg: false)
            
            if pageType == .typeDetail{
                
                contentTextView.isEditable = false
            }
        }else{
            
            DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                self.contentTextView.becomeFirstResponder()
            }
        }
        
    }

    func configImgCount(isPickImg:Bool) -> Bool{
        
        let attr = contentTextView.attributedText
        var imgCount:Int = 0
        
        delegate?.attriButeEditing?(attriStr: attr)
        
        attr!.enumerateAttributes(in: NSMakeRange(0, attr!.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, range, stop) in
            
            if let textAtt:NSTextAttachment = object[NSAttributedString.Key(rawValue: "NSAttachment")] as? NSTextAttachment {
                
                if textAtt.image != nil{

                    imgCount = imgCount+1
                }
            }
        }
        if isPickImg{
            
            if imgCount == 6 {
                SVProgressHUD.showSuccess(withStatus: "图片数量已达上限")
                SVProgressHUD.dismiss(withDelay: 1.0) {
                    
                }
                return false
            }else{
                return true
            }
                
        }else{
            
            imgCountLabel.text = "\(imgCount)" + "/6"
            
            return true
        }
        
    }
    
    func configActiveImagesNames(){
        
        if var imgArray = UserDefaults.standard.array(forKey: KUSERActiveImagesArrName ) as? [[String:Any]] {
            
            if let deletedImgArray = UserDefaults.standard.array(forKey: KUSERActiveDeletedImagesArrName) as? [[String:Any]] {
                imgArray.append(contentsOf: deletedImgArray)
            }
            reasonArray = imgArray
        }

    }
    
    func configKeybordAction(){
        
        NotificationCenter.default.rac_addObserver(forName: UIResponder.keyboardWillShowNotification.rawValue, object: nil)?.subscribeNext({ [weak self] (x) in
            
            guard let self = self else { return }

            let noti: Notification = x as! Notification
            let keyBoardH = (noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect).size.height
            let time = noti.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
            
            UIView.animate(withDuration: time*2) {
                self.textViewBottomConstraint.constant = keyBoardH+safeBottom_height
            }
            
        })
        NotificationCenter.default.rac_addObserver(forName: UIResponder.keyboardWillHideNotification.rawValue, object: nil)?.subscribeNext({ [weak self] (x) in
            
            guard let self = self else { return }
            
            let noti: Notification = x as! Notification
            let time = noti.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
            UIView.animate(withDuration: time) {
                self.textViewBottomConstraint.constant = 103
            }
        })
    }
    
    func continueEditFunc(){
        
        if let _:Data = UserDefaults.standard.data(forKey: textView_cache) {

            self.showReEditView()
        }

    }
    
    func showReEditView(){
        
        let alertC = UIAlertController.init(title: "提示", message: "是否继续上一次的编辑", preferredStyle: .alert)
        let alert = UIAlertAction.init(title: "编辑", style: .destructive) { [self]
            (UIAlertAction) in
            
            print("确定按钮点击")
            if let textviewCacheData:Data = UserDefaults.standard.data(forKey: textView_cache) {

                let attr:NSAttributedString = NSKeyedUnarchiver.unarchiveObject(with: textviewCacheData) as! NSAttributedString
                let mutableAttr = NSMutableAttributedString.init(attributedString: attr)
            
                attr.enumerateAttributes(in: NSMakeRange(0, attr.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, range, stop) in
                    
                    if let textAtt:NSTextAttachment = object[NSAttributedString.Key(rawValue: "NSAttachment")] as? NSTextAttachment {
                        
                        let tempImage:UIImage = textAtt.image!;
                        
                        let scale = tempImage.size.width / tempImage.size.height;
                        var height = 80.0;
                        var width = scale * height;
                        if (scale > 1){
                            width = 80;
                            height = width/scale;
                        }
                        
                        textAtt.bounds = CGRect(x: 0, y: 0, width: width, height: height)
                        mutableAttr.replaceCharacters(in: range, with: NSAttributedString.init(attachment: textAtt))
                    }
                }
                contentTextView.attributedText = mutableAttr.copy() as? NSAttributedString
                
            }

            
            UserDefaults.standard.set(nil, forKey: textView_cache)
            
        }
        let cancleAlert = UIAlertAction.init(title: "取消", style: .cancel) { (UIAlertAction) in
            
            print("点击取消按钮")
            UserDefaults.standard.set(nil, forKey: textView_cache)
        }

        alertC.addAction(cancleAlert)
        alertC.addAction(alert)

        self.present(alertC, animated: true, completion: nil)
        
    }
    
    @IBAction func pickImgAction(_ sender: Any) {
        
        view.endEditing(true)
        if self.configImgCount(isPickImg: true) == false{
            return
        }
        
        photoStyleChooseView = PhotoStyleChooseView.init(frame: CGRect(x: 0, y: 0, width: screen_width, height: screen_height), type: PageTypePickPhoto)
        self.view.addSubview(photoStyleChooseView)
        
        photoStyleChooseView.albumBlock = { [weak self] in
            
            //设置代理
            self?.imgPickerVC.delegate = self
            //设置image picker的用户界面
            self?.imgPickerVC.sourceType = .photoLibrary
            //设置图片选择控制器导航栏的背景颜色
            self?.imgPickerVC.navigationBar.barTintColor = UIColor.orange
            //设置图片选择控制器导航栏的标题颜色
            self?.imgPickerVC.navigationBar.titleTextAttributes = [.foregroundColor:UIColor.white]
            //设置图片选择控制器导航栏中按钮的文字颜色
            self?.imgPickerVC.navigationBar.tintColor = UIColor.white
            //显示图片选择控制器
            self?.present(self!.imgPickerVC , animated: true, completion: nil)
            
        }
        
        
        photoStyleChooseView.cameraBlock = { [weak self] in
            
            let cameraAuth = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
            if cameraAuth == AVAuthorizationStatus.denied || cameraAuth == AVAuthorizationStatus.restricted{
                
                SVProgressHUD.showError(withStatus: "请到设置->相机中打开APP的相机权限")
                SVProgressHUD.dismiss(withDelay: 2.0)
                return
            }
            
            //设置代理
            self?.imgPickerVC.delegate = self
            //设置image picker的用户界面
            self?.imgPickerVC.sourceType = .camera
            //设置图片选择控制器导航栏的背景颜色
            self?.imgPickerVC.navigationBar.barTintColor = UIColor.orange
            //设置图片选择控制器导航栏的标题颜色
            self?.imgPickerVC.navigationBar.titleTextAttributes = [.foregroundColor:UIColor.white]
            //设置图片选择控制器导航栏中按钮的文字颜色
            self?.imgPickerVC.navigationBar.tintColor = UIColor.white
            //显示图片选择控制器
            self?.present(self!.imgPickerVC, animated: true, completion: nil)
            
        }

    }
    @IBAction func addTimeAction(_ sender: Any) {
        
//        self.timeLabel.text = NSString.getHourAndMinute(NSString.currentTimeStamp())
        
        let timeStr = " " + NSString.getHourAndMinute(NSString.currentTimeStamp()) + " " + NSString.getChineseHourDescription() + " "
        
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 8
        let dic:Dictionary = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.paragraphStyle:paragraphStyle]
        
        let timeAttr = NSAttributedString.init(string: timeStr, attributes: dic)
        let range = contentTextView.selectedRange
        contentTextView.textStorage.replaceCharacters(in: range, with: timeAttr)
        contentTextView.selectedRange = NSMakeRange(range.location+timeStr.count, 0)
        
    }
    @IBAction func changeAligAction(_ sender: Any) {
        
        if contentTextView.textAlignment == .left{
            
            contentTextView.textAlignment = .center
            alagnBtn.setImage(UIImage.init(named: "字体对齐图标"), for: .normal)
        }else if contentTextView.textAlignment == .center{
            
            contentTextView.textAlignment = .right
            alagnBtn.setImage(UIImage.init(named: "字体对齐图标右"), for: .normal)
        }else{
            
            contentTextView.textAlignment = .left
            alagnBtn.setImage(UIImage.init(named: "字体对齐图标左"), for: .normal)
        }
        
    }
    @objc func saveAction() {
        
            
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        if pageType == .typeDetail{
            
            self.showEditAlert(timeStampStr: diaryDict?["timeStampStr"] as? String ?? "")
            return
        }
        
        for subView in view.subviews {
            subView.isUserInteractionEnabled = false
        }

        if diaryModel?.createTimeStampStr == nil {
            diaryModel?.createTimeStampStr = NSString.currentTimeStamp()
        }
        
        if (contentTextView.attributedText != nil) {
            
            var str = "isAttributedString"
            if contentTextView.textAlignment == .center{
                str = "1"+str
            }else if contentTextView.textAlignment == .right{
                str = "2"+str
            }else{
                str = "0"+str
            }
            
            diaryModel?.reasonDetailStr = str //显示时检测是否是此字符串，以此判断显示富文本还是普通文字
           
        }else{
            
            if contentTextView.text.count > 0 && contentTextView.text != "有更多想告诉我的吗？" {
                diaryModel?.reasonDetailStr = contentTextView.text
            } else {
                diaryModel?.reasonDetailStr = ""
            }
        }
        
        if pageType == .typeEdit{
            
            if Int(UserDefaults.standard.integer(forKey: "payStatus")) == 0{
                if  NSDate().timeIntervalSince1970 - Double(UserDefaults.standard.integer(forKey: "payTime")) >=  604800 {
                    SVProgressHUD.showError(withStatus: "请付费订阅继续使用")
                    SVProgressHUD.dismiss(withDelay: 2.0) {
                        let vc = PayViewController()
                        vc.modalPresentationStyle = .fullScreen
                        self.present(vc, animated: true, completion: nil)
                    }
                    return
                }
            }
            
            diaryDict?["reasonDetailStr"] = diaryModel?.reasonDetailStr
            
            delegate?.attributeEditDone?(dict: diaryDict as NSDictionary?,attriStr: contentTextView.attributedText)
                
            let vcIndex:Int = (navigationController?.viewControllers.count)!-1
            let vc = navigationController?.viewControllers[vcIndex-2]
            navigationController?.popToViewController(vc!, animated: true)
//
            return
        }
//        604800
        
        if Int(UserDefaults.standard.integer(forKey: "payStatus")) == 0{
            if  NSDate().timeIntervalSince1970 - Double(UserDefaults.standard.integer(forKey: "payTime")) >=  604800 {
                SVProgressHUD.showError(withStatus: "请付费订阅继续使用")
                SVProgressHUD.dismiss(withDelay: 2.0) {
                    let vc = PayViewController()
                    vc.modalPresentationStyle = .fullScreen
                    self.present(vc, animated: true, completion: nil)
                }
                return
            }
        }
        
        
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(diaryModel)
            let dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            
            let fileManager = FileManager.default
            let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
            var folderPath = docPath + "/" + NSString.currentYear()
            
            if NSString.getYear(diaryModel?.timeStampStr ?? "") != NSString.currentYear() {
                folderPath = docPath + "/" + "\((Int(NSString.currentYear()) ?? 0) - 1)"
            }

            if fileManager.fileExists(atPath: folderPath) == false {
                do {
                    try fileManager.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    print(error)
                }
            }
            let fileName = NSString.getMonth(diaryModel?.timeStampStr ?? "") + ".plist"

            let filePath = (folderPath as NSString).appendingPathComponent(fileName)

            var hisDictionary = NSMutableDictionary(contentsOfFile: filePath)
            if hisDictionary == nil {
                hisDictionary = NSMutableDictionary()
            }

            let day = NSString.getDay(diaryModel?.timeStampStr ?? "")

            var dayArray: [[String: Any]]? = hisDictionary?[day] as? [[String: Any]]
            if dayArray == nil {
                dayArray = [[String: Any]]()
            }
            dayArray?.append(dict as! [String : Any])
            hisDictionary?[day] = dayArray
            
            
            //富文本储存
            var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
            url?.appendPathComponent((diaryModel?.timeStampStr)! + ".txt")
            
            let attriStrData = NSKeyedArchiver.archivedData(withRootObject: contentTextView.attributedText as Any)
            do {
                try attriStrData.write(to: url!)
            } catch {
                print(error)
            }

            
            
            
            //日记
            let diaryFilePath = docPath + "/diary.plist"
            var diaryArr = NSMutableArray(contentsOfFile: diaryFilePath)
            if diaryArr == nil {
                diaryArr = NSMutableArray()
            }
            diaryArr?.add(dict)
            diaryArr?.write(toFile: diaryFilePath, atomically: true)
            
            
            
            //心情
            let moodDic = ["mood": diaryModel?.moodStr, "timeStamp": diaryModel?.timeStampStr]
            let moodFilePath = docPath + "/mood.plist"
            var moodArr = NSMutableArray(contentsOfFile: moodFilePath)
            if moodArr == nil {
                moodArr = NSMutableArray()
            }
            moodArr?.add(moodDic)
            moodArr?.write(toFile: moodFilePath, atomically: true)

            //天气
            let weatherDic = ["weather": diaryModel?.weatherStr, "timeStamp": diaryModel?.timeStampStr]
            let weatherFilePath = docPath + "/weather.plist"
            var weatherArr = NSMutableArray(contentsOfFile: weatherFilePath)
            if weatherArr == nil {
                weatherArr = NSMutableArray()
            }
            weatherArr?.add(weatherDic)
            weatherArr?.write(toFile: weatherFilePath, atomically: true)

            //活动
            let activityFilePath = docPath + "/activity.plist"
            var activityArr = NSMutableArray(contentsOfFile: activityFilePath)
            if activityArr == nil {
                activityArr = NSMutableArray()
            }

            for activity in diaryModel?.reasonArray ?? [] {
                let reasonDic = ["activity": activity, "timeStamp": diaryModel?.timeStampStr]
                activityArr?.add(reasonDic)
            }
            activityArr?.write(toFile: activityFilePath, atomically: true)

            let flag = hisDictionary?.write(toFile: filePath, atomically: true)
            if flag == true {

                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "createSucceed"), object: nil)
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "addDone"), object: nil)

                if pageType == .typeNew{
                    
                    SVProgressHUD.showSuccess(withStatus: "创建成功")
                    SVProgressHUD.dismiss(withDelay: 2.0) {
                        // 坏心情提供弹层
                        
                        self.dismiss(animated: true) { [weak self] in
                            guard let `self` = self else {return}

                            if self.isBadXinqing {
                                self.showComfortDialogue()
                            }
                        }
                    }
                }else if pageType == .typeEdit{
                    
                    SVProgressHUD.showSuccess(withStatus: "保存成功")
                    SVProgressHUD.dismiss(withDelay: 1.0) {
                        
                        self.navigationController?.popToRootViewController(animated: true)
                    }
                }
            } else {
                SVProgressHUD.showError(withStatus: "创建失败")
                SVProgressHUD.dismiss(withDelay: 2.0)
                navigationItem.rightBarButtonItem?.isEnabled = true
            }
            
            UserDefaults.standard.set(nil, forKey: textView_cache)
            
        } catch {
            print(error)
        }

        
        NSLog("保存")
    }
    
    func showEditAlert(timeStampStr:String){
        
        let photoStyleChooseView:PhotoStyleChooseView = PhotoStyleChooseView.init(frame:CGRect(x: 0, y: 0, width: screen_width, height: screen_height), type: .init(rawValue: 1))

        let window = UIApplication.shared.keyWindow
        window?.addSubview(photoStyleChooseView)

        photoStyleChooseView.albumBlock = { [weak self] in
            
            self?.jumpToEdit()
        }
        
        photoStyleChooseView.cameraBlock = { [weak self] in
            
            
            self?.deleteRowAlert()

        }
    }
    
    func jumpToEdit() {
        
        let vc = DiaryEditViewController()
        vc.dic = diaryDict
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    
    func deleteRowAlert() {
        self.presentedViewController?.dismiss(animated: true, completion: nil)
        let alertVC = UIAlertController(title: "提示", message: "确定删除这条数据?", preferredStyle: UIAlertController.Style.actionSheet)
        alertVC.addAction(UIAlertAction(title: "删除", style: UIAlertAction.Style.default, handler: { [weak self] action in
            // 删除
            self?.delegate?.diaryDelete?(index: self?.editIndex ?? -1, timeStamp: self?.diaryDict?["timeStampStr"] as? String ?? "")
            self?.navigationController?.popViewController(animated: true)
        }))
        
        alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.destructive, handler: { action in
            // 取消
        }))
        
        self.present(alertVC, animated: true, completion: nil)
    }

    
    @objc func closeAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
    private func showComfortDialogue() {
        
        if self.checkTodayDiary(timeStamp: diaryModel?.timeStampStr ?? ""){
            
            let saveView = DiarySaveSuccessView()
            saveView.frame.size = .init(width: 280, height: 275)
            saveAlert = CustomDialogueController.create(with: saveView)
            weak var weakSaveAlert = saveAlert
            saveView.didTouchUpInside {
                weakSaveAlert?.dismiss(animated: true, completion: nil)
                
                let dialogue = ComfortDialogueView()
                dialogue.frame.size = .init(width: AppWidth - 40, height: (AppWidth - 40)*0.88)
                self.alert = CustomDialogueController.create(with: dialogue)
                weak var weakAlert = self.alert
                dialogue.didTouchUpInside {
                    weakAlert?.dismiss(animated: true, completion: nil)
                }
                
                UIApplication.shared.keyWindow?.rootViewController?.present(self.alert!, animated: true)
            }
            
            UIApplication.shared.keyWindow?.rootViewController?.present(saveAlert!, animated: true)
            
        }else{
            
            let dialogue = ComfortDialogueView()
            dialogue.frame.size = .init(width: AppWidth - 40, height: (AppWidth - 40)*0.88)
            self.alert = CustomDialogueController.create(with: dialogue)
            weak var weakAlert = self.alert
            dialogue.didTouchUpInside {
                weakAlert?.dismiss(animated: true, completion: nil)
            }
            
            UIApplication.shared.keyWindow?.rootViewController?.present(self.alert!, animated: true)
            
        }
        
    }
    
    private func checkTodayDiary(timeStamp:String) -> Bool{//检查是否是当天第一个日记

        //日记必有心情，用心情的时间戳来判断当天是否已经有过日记
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String

        let moodFilePath = docPath + "/mood.plist"
        let moodArr = NSMutableArray(contentsOfFile: moodFilePath) as! [[String:String]]

        for dict in moodArr {
            
            let tempTimeStamp:String = dict["timeStamp"] ?? ""
            let diaryTimeStamp:String = timeStamp
            
            if NSString.getYear(tempTimeStamp) == NSString.getYear(diaryTimeStamp) && NSString.getMonth(tempTimeStamp) == NSString.getMonth(diaryTimeStamp) && NSString.getDay(tempTimeStamp) == NSString.getDay(diaryTimeStamp){
                
                return false
            }
            
        }
        
        return true
        
  
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        view.endEditing(true)
    }
    
    @objc func addImage(image: UIImage) {
        //创建文本附件
        let attachment = NSTextAttachment()
        //设置附件的图片
        attachment.image = image
        //图片的缩放比例
        let scale = image.size.width / image.size.height
        var height = 80.0
        var width = scale * height
        if scale > 1{
            width = 80
            height = width/scale
        }
        
        //设置附件的大小
        attachment.bounds = CGRect(x: 0, y: 0, width: width, height: height)
        //获取textView中的富文本
        let attribute = NSAttributedString.init(attachment: attachment)
        
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 8
        let dic:Dictionary = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.paragraphStyle:paragraphStyle]
        let tempAttr = NSMutableAttributedString.init(attributedString: attribute)
        tempAttr.addAttributes(dic, range: NSMakeRange(0, tempAttr.string.count))
        
        let range = contentTextView.selectedRange
        
        //在富文本中加入图片附件
        //textStorage装载内容的容器,继承自NSMutableAttributedString,其里面保存的东西决定了textview的富文本显示方式
        contentTextView.textStorage.replaceCharacters(in: range, with: ((tempAttr.copy() as? NSAttributedString)!))
        
        contentTextView.selectedRange = NSMakeRange(range.location+1, 0)
        
        contentTextView.typingAttributes = dic
        
        self.configImgCount(isPickImg: false);
        
    }
    
    
}
    
extension AddDiaryContentViewController: DiaryEditViewControllerDelegate {
    func diaryEditDone(dic: NSDictionary?, editIndex: Int, attriStr: NSAttributedString?) {
        
        if pageType != .typeDetail{
            return
        }
        
        diaryDict?["timeStampStr"] = dic?["timeStampStr"] as? String
        diaryDict?["moodStr"] = dic?["moodStr"] as? String
        diaryDict?["weatherStr"] = dic?["weatherStr"] as? String
        diaryDict?["reasonArray"] =  dic?["reasonArray"] as? Array<String>
        diaryDict?["reasonDetailStr"] = dic?["reasonDetailStr"] as? String
        diaryDict?["createTimeStampStr"] = dic?["createTimeStampStr"] as? String

        diaryModel?.timeStampStr = diaryDict?["timeStampStr"] as? String
        diaryModel?.moodStr = diaryDict?["moodStr"] as? String
        diaryModel?.weatherStr = diaryDict?["weatherStr"] as? String
        diaryModel?.reasonArray = diaryDict?["reasonArray"] as? Array
        diaryModel?.reasonDetailStr = diaryDict?["reasonDetailStr"] as? String
        diaryModel?.createTimeStampStr = diaryDict?["createTimeStampStr"] as? String
        
        tempAttrStr = attriStr
        
        self.configUI()
        
        delegate?.attributeEditDone?(dict: dic,attriStr: attriStr)
        
    }
}

extension AddDiaryContentViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    /// 图片选择完成
    ///
    /// - Parameters:
    /// - picker: 图片选择控制器
    /// - info: 图片信息
    ///
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        //获取选择到的图片
        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        
        let tempImg = UIImage.compressImage(image, toByte: 1024*50)
        
        //将图片加入到textView中
        addImage(image: tempImg)
        //关闭当前界面
        self.dismiss(animated: true, completion: nil)
    }
    /// 取消选择图片
    ///
    /// - Parameter picker: 图片选择控制器
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
    
}


extension AddDiaryContentViewController: UITextViewDelegate {
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        
        return true
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

//        mutableAttr.setAttributes([NSAttributedString.Key.baselineOffset:10], range: NSMakeRange(0, mutableAttr.string.count))
//        contentTextView.attributedText = mutableAttr.copy() as? NSAttributedString
        
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 8
        let dic:Dictionary = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.paragraphStyle:paragraphStyle]
        textView.typingAttributes = dic
        return true
    }

    func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        
        self.showBigPhoto(textAttachment: textAttachment)
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        self.configImgCount(isPickImg: false)
        
        let attriStrData = NSKeyedArchiver.archivedData(withRootObject: contentTextView.attributedText as Any)
        
        UserDefaults.standard.set(attriStrData, forKey: textView_cache)
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        
//        if textView.text == "" {
//
//            textView.textColor = UIColor.hexColor(hex: "#8f8f8f")
//            textView.text = "有更多想告诉我的吗？"
//        }
    }
    
    func showBigPhoto(textAttachment: NSTextAttachment) -> Void {
        
        if let tempImage:UIImage = textAttachment.image {
            
            HUPhotoBrowser.show(from: nil, withImages: [tempImage], at: 0)
        }
    }
}



extension AddDiaryContentViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return diaryModel?.reasonArray?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let text:String = diaryModel?.reasonArray?[indexPath.item] ?? ""
        
        let desLabel:UILabel = UILabel.init()
        desLabel.numberOfLines = 0
        let font:UIFont = UIFont.systemFont(ofSize: 14)
        desLabel.text = text

        var size:CGSize = CGSize(width: 120, height: 500);//跟label的宽设置一样
        let dic:Dictionary = [NSAttributedString.Key.font:font]
        size = (desLabel.text?.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic, context: nil).size)!
        return CGSize(width: 32.0 + size.width, height: 20.0)
        
    }
    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell: ActiveCollectionCellForDiaryContentEditPage = collectionView.dequeueReusableCell(withReuseIdentifier: "ActiveCollectionCellForDiaryContentEditPage", for: indexPath) as! ActiveCollectionCellForDiaryContentEditPage
        
        cell.textLabel?.text = diaryModel?.reasonArray?[indexPath.item]
        
        for dic in reasonArray {
            
            if dic["text"] as? String == cell.textLabel?.text{
                
                cell.imgView?.image = UIImage(named: dic["imgName"] as? String ?? "" )
                break
            }
            
        }

        
        if indexPath.row == (diaryModel?.reasonArray?.count ?? 1) - 1 {
            cell.pointView?.isHidden = true
        } else {
            cell.pointView?.isHidden = false
        }
        return cell


        
    }
    
  
    
}


